<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="网站名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入网站名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="applyTime">
        <el-date-picker clearable
          v-model="queryParams.applyTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 链接状态标签页 -->
    <div class="link-tabs">
      <div class="tab-item" :class="{ active: activeTab === 'all' }" @click="handleTabSwitch('all')">所有友链</div>
      <div class="tab-item" :class="{ active: activeTab === 'pending' }" @click="handleTabSwitch('pending')">待审核</div>
      <div class="tab-item" :class="{ active: activeTab === 'approved' }" @click="handleTabSwitch('approved')">审核通过</div>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:link:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:link:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:link:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Check"
          :disabled="multiple"
          @click="handleBatchApprove"
          v-hasPermi="['manage:link:edit']"
        >批量审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:link:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="linkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="网站头像" align="center" prop="avatar" width="100">
        <template #default="scope">
          <el-image 
            v-if="scope.row.avatar" 
            :src="scope.row.avatar" 
            style="width: 50px; height: 50px; border-radius: 50%;"
            :preview-src-list="[scope.row.avatar]"
            fit="cover"
            :initial-index="0"
          />
          <el-image 
            v-else 
            src="/src/assets/images/default-avatar.png" 
            style="width: 50px; height: 50px; border-radius: 50%;"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="网站名称" align="center" prop="name" />
      <el-table-column label="网站链接" align="center" prop="url">
        <template #default="scope">
          <a :href="scope.row.url" target="_blank">{{ scope.row.url }}</a>
        </template>
      </el-table-column>
      <el-table-column label="网站描述" align="center" prop="description" />
      <el-table-column label="审核状态" align="center" prop="isApproved" width="100">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.isApproved == 1">已通过</el-tag>
          <el-tag type="warning" v-else>待审核</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="approveTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.approveTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:link:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:link:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改友情链接对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="linkRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="网站名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入网站名称" />
        </el-form-item>
        <el-form-item label="网站链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入网站链接" />
        </el-form-item>
        <el-form-item label="网站描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="网站图标" prop="avatar">
          <el-input v-model="form.avatar" placeholder="请输入网站图标" />
        </el-form-item>
        <el-form-item label="审核状态" prop="isApproved">
          <el-select v-model="form.isApproved" placeholder="请选择审核状态">
            <el-option :value="0" label="待审核"></el-option>
            <el-option :value="1" label="已通过"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Link">
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue'
import { listLink, getLink, delLink, addLink, updateLink } from "@/api/manage/link"

const { proxy } = getCurrentInstance()

const linkList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const activeTab = ref("all")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    applyTime: null,
  },
  rules: {
    name: [
      { required: true, message: "网站名称不能为空", trigger: "blur" }
    ],
    url: [
      { required: true, message: "网站链接不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 处理标签页点击 */
function handleTabSwitch(tab) {
  activeTab.value = tab
  queryParams.value.pageNum = 1
  
  // 根据tab状态直接设置isApproved参数
  if (tab === 'approved') {
    // 这里有调用前端接口，从数据库中只查询isApproved为1的数据
    queryParams.value.isApproved = 1
  } else if (tab === 'pending') {
    // 这里有调用前端接口，从数据库中只查询isApproved为0的数据
    queryParams.value.isApproved = 0
  } else {
    // 这里调用前端接口，从数据库查询所有数据
    delete queryParams.value.isApproved
  }
  
  getList()
}

/** 查询友情链接列表 */
function getList() {
  loading.value = true
  
  listLink(queryParams.value).then(response => {
    linkList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    url: null,
    description: null,
    avatar: null,
    isApproved: null,
    applyTime: null,
    approveTime: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("linkRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 重置时确保移除isApproved参数
  delete queryParams.value.isApproved
  // 重置tab状态
  activeTab.value = 'all'
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加友情链接"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getLink(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改友情链接"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["linkRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateLink(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addLink(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除友情链接编号为"' + _ids + '"的数据项？').then(function() {
    return delLink(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/link/export', {
    ...queryParams.value
  }, `link_${new Date().getTime()}.xlsx`)
}

/** 批量审核按钮操作 */
/** 
 * 批量审核按钮操作
 * 将选中的记录状态从待审核改为已通过，并更新审核时间
 */
function handleBatchApprove() {
  if (ids.value.length === 0) {
    proxy.$modal.msgError("请至少选择一条记录")
    return
  }
  
  proxy.$modal.confirm('是否批量审核通过选中的' + ids.value.length + '条记录？').then(function() {
    // 获取当前选中的所有记录
    const selectedRows = linkList.value.filter(row => ids.value.includes(row.id))
    
    // 创建批量更新的请求数组
    const promises = selectedRows.map(row => {
      // 创建更新对象，只包含必要的字段
      const updateData = {
        id: row.id,
        isApproved: 1,
        approveTime: new Date()
      }
      return updateLink(updateData)
    })
    
    // 等待所有更新完成
    return Promise.all(promises)
  }).then(() => {
    // 刷新列表数据
    getList()
    proxy.$modal.msgSuccess("批量审核成功")
  }).catch((error) => {
    console.error("批量审核失败:", error)
    proxy.$modal.msgError("批量审核失败，请重试")
  })
}

// Initialize component
onMounted(() => {
  // 设置初始标签状态为"所有友链"
  activeTab.value = 'all'
  // 确保没有筛选条件
  delete queryParams.value.isApproved
  // 加载数据
  getList()
})
</script>

<style scoped>
.link-tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #e6e6e6;
}

.tab-item {
  padding: 8px 20px;
  cursor: pointer;
  position: relative;
  color: #606266;
  font-size: 14px;
}

.tab-item.active {
  color: #1890ff;
  font-weight: normal;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #1890ff;
}
</style>
